package com.dinadi.yidi.ui.activity;

import android.content.Intent;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.adapter.DesignerWorksAdapter;
import com.dinadi.yidi.adapter.ItemDesignerHomePageAdapter;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.CollectionBean;
import com.dinadi.yidi.bean.DesignerWorksBean;
import com.dinadi.yidi.bean.DesignerWorksRequst;
import com.dinadi.yidi.bean.DesignerWorksRequstEntity;
import com.dinadi.yidi.bean.ListBean;
import com.dinadi.yidi.bean.ProductSubjectListBean;
import com.dinadi.yidi.bean.ShareBean;
import com.dinadi.yidi.bean.UserInformationBean;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.http.interfaces.IntegralChangeInterface;
import com.dinadi.yidi.utils.EmptyUtils;
import com.dinadi.yidi.utils.ImageUtils;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.pullloadmorerecyclerview.PullLoadMoreRecyclerView;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * author: JiaYu.He
 * Date: 2018/5/15   设计师主页（改版）
 * Time: 10:19
 */

public class DesignerHmePageActivity extends BaseActivity {
    private View view;
    private TextView tvTitle, nick_name, brand_name, signature, follow_num, tv_follow;
    private RelativeLayout layout_brand_story;
    private CircleImageView head_img;
    private ImageView follow, img_designer;
    private PullLoadMoreRecyclerView mPullLoadMoreRecyclerView;
    private DesignerWorksAdapter mRefreshAdapter;
    private String userId, dUserId, token;
    private String htmlPath, nickName, headImg, haveFlow, status, brandName, signatures, coverImg;
    private List<DesignerWorksRequstEntity> dataList = new ArrayList<>();
    private List<ProductSubjectListBean> zkDataBean = new ArrayList<>();
    private List<ProductSubjectListBean> newDataBean = new ArrayList<>();
    private int page = 1;
    /*判断是否登陆*/
    private boolean loginState;

    private GridView gv_new, gv_zk;
    private ItemDesignerHomePageAdapter new_adapter, zk_adapter;
    private RelativeLayout layout_new, layout_zk;


    @Override
    protected View getLayout() {
        view = LayoutInflater.from(DesignerHmePageActivity.this).inflate(R.layout.activity_designer_homepage2, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    public void onResume() {
        super.onResume();
        String isRefresh = SharePreferencesHelper.getInstance(DesignerHmePageActivity.this).getString("isRefresh");
        if ("yes".equals(isRefresh)) {
            userId = SharePreferencesHelper.getInstance(DesignerHmePageActivity.this).getString("userId");
            token = SharePreferencesHelper.getInstance(DesignerHmePageActivity.this).getString("token");
            loginState = SharePreferencesHelper.getInstance(this).getBoolean("loginState");
            SharePreferencesHelper.getInstance(DesignerHmePageActivity.this).putString("isRefresh", "no");
        }
    }

    @Override
    protected void initView() {
        changePager(2);
        tvTitle = (TextView) view.findViewById(R.id.text_title);
        layout_brand_story = (RelativeLayout) view.findViewById(R.id.layout_brand_story);
        head_img = (CircleImageView) view.findViewById(R.id.head_img);
        nick_name = (TextView) view.findViewById(R.id.nick_name);
        brand_name = (TextView) view.findViewById(R.id.brand_name);
        signature = (TextView) view.findViewById(R.id.signature);
        follow_num = (TextView) view.findViewById(R.id.follow_num);
        follow = (ImageView) view.findViewById(R.id.follow);
        img_designer = (ImageView) view.findViewById(R.id.img_designer);
        mPullLoadMoreRecyclerView = (PullLoadMoreRecyclerView) view.findViewById(R.id.pullLoadMoreRecyclerView);
        mPullLoadMoreRecyclerView.setGridLayout(2);
        mRefreshAdapter = new DesignerWorksAdapter(DesignerHmePageActivity.this);
        mPullLoadMoreRecyclerView.setAdapter(mRefreshAdapter);
        mPullLoadMoreRecyclerView.setOnPullLoadMoreListener(new PullLoadMoreListener());
        mPullLoadMoreRecyclerView.setPullRefreshEnable(false);
        gv_new = (GridView) view.findViewById(R.id.gv_homepage);
        gv_zk = (GridView) view.findViewById(R.id.gv_homepage2);
        layout_new = (RelativeLayout) view.findViewById(R.id.layout_new);
        layout_zk = (RelativeLayout) view.findViewById(R.id.layout_zk);
        new_adapter = new ItemDesignerHomePageAdapter(DesignerHmePageActivity.this, newDataBean);
        gv_new.setAdapter(new_adapter);
        zk_adapter = new ItemDesignerHomePageAdapter(DesignerHmePageActivity.this, zkDataBean);
        gv_zk.setAdapter(zk_adapter);

    }

    @Override
    protected void initListener() {
        registerClickListener(layout_brand_story, follow, layout_new, layout_zk);
        mRefreshAdapter.setmOnItemClickListener(new DesignerWorksAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, String data) {
                Intent intent = new Intent(DesignerHmePageActivity.this, ProductDetailsActivity.class);
                intent.putExtra("productId", data);
                startActivity(intent);
                MobclickAgent.onEvent(DesignerHmePageActivity.this, "DesignerHaveFlow", "设计师");
            }
        });

    }

    @Override
    protected void initData() {
        token = SharePreferencesHelper.getInstance(this).getString("token");
        userId = SharePreferencesHelper.getInstance(this).getString("userId");
        loginState = SharePreferencesHelper.getInstance(this).getBoolean("loginState");
        Intent intent = getIntent();
        dUserId = intent.getStringExtra("dUserId");
        designersData();
    }

    @Override
    protected void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.layout_brand_story:
                Intent intent = new Intent(DesignerHmePageActivity.this, DesignerBrandStoryActivity.class);
                intent.putExtra("name", nickName + "的品牌故事");
                intent.putExtra("htmlPath", htmlPath);
                intent.putExtra("nickName", nickName);
                intent.putExtra("headImg", headImg);
                intent.putExtra("brandName", brandName);
                intent.putExtra("signature", signatures);
                intent.putExtra("coverImg", coverImg);
                intent.putExtra("dUsetID", dUserId);
                startActivity(intent);
                MobclickAgent.onEvent(DesignerHmePageActivity.this, "DesignerBrandStory", "设计师品牌故事");
                break;
            case R.id.follow:
                if (loginState == false) {
                    Intent loginIntent = new Intent();
                    loginIntent.setClass(this, LoginActivity.class);
                    startActivity(loginIntent);
                } else {
                    if (haveFlow.equals("0")) {
                        //否  进行关注
                        status = "1";
                        follow.setImageResource(R.drawable.icon_follow_selected_big);
                        MobclickAgent.onEvent(DesignerHmePageActivity.this, "DesignerHaveFlow", "关注设计师");

                    } else if (haveFlow.equals("1")) {
                        //是  取消关注
                        status = "0";
                        follow.setImageResource(R.drawable.icon_follow_pressed_big);

                    }
                    CollectionBean bean = new CollectionBean();
                    bean.setToken(token);
                    bean.setStatus(status);
                    bean.setUserId(userId);
                    bean.setTargerUserId(dUserId);
                    CommonInterface userInformationInetrface = new CommonInterface(DesignerHmePageActivity.this, collectionHttpListener);
                    userInformationInetrface.getInterface("11009", JSON.toJSONString(bean));
                }

                break;
            case R.id.layout_new:
                Intent intent2 = new Intent(DesignerHmePageActivity.this, ProductSubjectAllActivity.class);
                intent2.putExtra("userId", dUserId);
                intent2.putExtra("title", "新品");
                intent2.putExtra("type", "1");
                startActivity(intent2);
                break;
            case R.id.layout_zk:
                Intent intent3 = new Intent(DesignerHmePageActivity.this, ProductSubjectAllActivity.class);
                intent3.putExtra("title", "折扣");
                intent3.putExtra("userId", dUserId);
                intent3.putExtra("type", "2");
                startActivity(intent3);
                break;
            default:
                break;
        }

    }

    private void designersData() {
        UserInformationBean bean = new UserInformationBean();
        bean.setUserId(dUserId);
        bean.setToken(token);
        CommonInterface userInformationInetrface = new CommonInterface(DesignerHmePageActivity.this, httpListener);
        userInformationInetrface.getInterface("11008", JSON.toJSONString(bean));
    }

    private void initPullrefresh() {

        DesignerWorksBean bean = new DesignerWorksBean();
        //  bean.setToken(token);
        bean.setUserId(dUserId);
        bean.setPageNum(page + "");
        bean.setPageSize("10");
        CommonInterface designerWorksInterface = new CommonInterface(DesignerHmePageActivity.this, httpListener2);
        designerWorksInterface.getInterface("13002", JSON.toJSONString(bean));
    }

    /*获取活动*/
    private void obtainSpecial() {
        ShareBean bean = new ShareBean();
        bean.setUserId(dUserId);
        bean.setToken(token);
        CommonInterface messageInterface = new CommonInterface(DesignerHmePageActivity.this, specialListener);
        messageInterface.getInterface("13009", JSON.toJSONString(bean));

    }

    HttpListener httpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                closeLoadingDialog();
                nickName = JsonUtil.getFieldValue(response, "nickName");
                tvTitle.setText(nickName + "的主页");
                nick_name.setText(nickName);
                headImg = JsonUtil.getFieldValue(response, "headImg");
                coverImg = JsonUtil.getFieldValue(response, "coverImg");
                if (EmptyUtils.isNotEmpty(coverImg)) {
                    ImageUtils.loadImageView(DesignerHmePageActivity.this, coverImg, img_designer);

                } else {
                    ImageUtils.loadImageView(DesignerHmePageActivity.this, R.drawable.img_bitmap_designer, img_designer);

                }
                if (EmptyUtils.isNotEmpty(headImg)) {
                    ImageUtils.loadImageView(DesignerHmePageActivity.this, headImg, head_img);

                } else {
                    ImageUtils.loadImageView(DesignerHmePageActivity.this, R.drawable.symbols_bitmap_head_portrait, head_img);

                }

                brandName = JsonUtil.getFieldValue(response, "brandName");
                if (brandName.equals("null")) {
                    brand_name.setText("");

                } else {
                    brand_name.setText(brandName);
                }
//                d_userId = JsonUtil.getFieldValue(response, "userId");
                haveFlow = JsonUtil.getFieldValue(response, "haveFlow");
                if (haveFlow.equals("0")) {
                    //否
                    follow.setImageResource(R.drawable.icon_follow_pressed_big);
                } else {
                    //是
                    follow.setImageResource(R.drawable.icon_follow_selected_big);
                }
                signatures = JsonUtil.getFieldValue(response, "signature");
                if (signatures.equals("null")) {
                    signature.setText("");

                } else {
                    signature.setText(signatures);
                }
                String flowedNum = JsonUtil.getFieldValue(response, "flowedNum");
                follow_num.setText(flowedNum);
                SharePreferencesHelper.getInstance(DesignerHmePageActivity.this).putString("brandName", brandName);
                String dUserId = JsonUtil.getFieldValue(response, "userId");
                SharePreferencesHelper.getInstance(DesignerHmePageActivity.this).putString("dUserId", dUserId);
                /*文章*/
                htmlPath = JsonUtil.getFieldValue(response, "htmlPath");
                SharePreferencesHelper.getInstance(DesignerHmePageActivity.this).putString("htmlPath", htmlPath);
                obtainSpecial();

            } else {
                closeLoadingDialog();
                toast(errMsg);
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            closeLoadingDialog();
            toast("加载失败");
        }
    };


    HttpListener httpListener2 = new HttpListener() {

        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                //  closeLoadingDialog();
                DesignerWorksRequst bean = JsonUtil.parseJsonToBean(response, DesignerWorksRequst.class);
                dataList = bean.getProductList();
                mRefreshAdapter.addAllData(dataList);
                getData();
            } else {
                toast(errMsg);
            }

        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("加载失败");
        }
    };
    /*关注*/
    HttpListener collectionHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            if (errCode.equals("0000")) {
                if (status.equals("1")) {
                    IntegralChangeInterface.IntegralChange(DesignerHmePageActivity.this, userId, token, "9", "1", "关注成功");
//                    follow.setImageResource(R.drawable.icon_follow_selected_big);
                } else {
                    IntegralChangeInterface.IntegralChange(DesignerHmePageActivity.this, userId, token, "9", "2", "取消关注");
//                    follow.setImageResource(R.drawable.icon_follow_pressed_big);
                }
                designersData();
            }
        }


        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("操作失败");
        }
    };
    HttpListener specialListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {

                ListBean bean = JsonUtil.parseJsonToBean(response, ListBean.class);
                newDataBean.addAll(bean.getNewProductList());
                zkDataBean.addAll(bean.getDiscountProductList());
                if (zkDataBean.size() == 0) {
                    layout_zk.setVisibility(View.GONE);
                } else {
                    zk_adapter.notifyDataSetChanged();
                }
                if (newDataBean.size() == 0) {
                    layout_new.setVisibility(View.GONE);
                } else {
                    new_adapter.notifyDataSetChanged();
                }
                initPullrefresh();
            } else {
                closeLoadingDialog();
                toast(errMsg);
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };

    private void getData() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新结束
                mPullLoadMoreRecyclerView.setPullLoadMoreCompleted();
            }
        }, 1000);
    }

    class PullLoadMoreListener implements PullLoadMoreRecyclerView.PullLoadMoreListener {
        @Override
        public void onRefresh() {
            setRefresh();
        }

        @Override
        public void onLoadMore() {
            page = page + 1;
            initPullrefresh();
        }

    }

    private void setRefresh() {
        mRefreshAdapter.clearData();
        page = 1;
        initPullrefresh();
    }
}
